import os
import time
import json
from gtts import gTTS
import pygame
from tqdm import tqdm

scriptPath = os.path.dirname(__file__)

class SleepLearning:
    def __init__(self):
        self.words_file = os.path.join(scriptPath, "02.md")
        self.audio_dir = os.path.join(scriptPath, "audio_files")
        self.progress_file = os.path.join(scriptPath, "progress.json")
        self.pause_duration = 3  # 单词间隔时间（秒）
        
        # 创建音频文件目录
        if not os.path.exists(self.audio_dir):
            os.makedirs(self.audio_dir)
            
        # 初始化进度
        self.progress = self.load_progress()
        
        # 初始化pygame音频
        pygame.mixer.init()

    def load_words(self):
        """加载单词列表"""
        with open(self.words_file, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f.readlines() if line.strip()]

    def load_progress(self):
        """加载学习进度"""
        if os.path.exists(self.progress_file):
            with open(self.progress_file, 'r') as f:
                return json.load(f)
        return {"learned_words": [], "current_index": 0}

    def save_progress(self):
        """保存学习进度"""
        with open(self.progress_file, 'w') as f:
            json.dump(self.progress, f)

    def generate_audio(self, word):
        """为单词生成音频文件"""
        audio_path = os.path.join(self.audio_dir, f"{word}.mp3")
        if not os.path.exists(audio_path):
            tts = gTTS(text=word, lang='en')
            tts.save(audio_path)
        return audio_path

    def play_audio(self, audio_path):
        """播放音频文件"""
        pygame.mixer.music.load(audio_path)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        time.sleep(self.pause_duration)

    def start_learning(self):
        """开始学习过程"""
        words = self.load_words()
        current_index = self.progress["current_index"]
        
        print(f"从第 {current_index + 1} 个单词开始学习...")
        
        try:
            for i in tqdm(range(current_index, len(words))):
                word = words[i]
                if word not in self.progress["learned_words"]:
                    print(f"\n当前学习: {word}")
                    audio_path = self.generate_audio(word)
                    self.play_audio(audio_path)
                    self.progress["learned_words"].append(word)
                    self.progress["current_index"] = i
                    self.save_progress()
        except KeyboardInterrupt:
            print("\n学习已暂停。进度已保存。")
            self.save_progress()

if __name__ == "__main__":
    learner = SleepLearning()
    learner.start_learning()
